import type { UserConfig } from 'vite';

import path from 'node:path';
import Uni from '@uni-helper/plugin-uni';
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts';
import UniManifest from '@uni-helper/vite-plugin-uni-manifest';
import UniPages from '@uni-helper/vite-plugin-uni-pages';
import UniPlatform from '@uni-helper/vite-plugin-uni-platform';
import UnoCSS from 'unocss/vite';

import { defineConfig, loadEnv } from 'vite';

export default defineConfig(async ({ mode }) => {
  const { UNI_PLATFORM } = process.env;
  const env = loadEnv(mode, path.resolve(process.cwd(), 'env'));
  const {
    VITE_APP_PORT,
    VITE_SERVER_BASEURL,
    VITE_DELETE_CONSOLE,
    VITE_SHOW_SOURCEMAP,
    VITE_APP_PROXY,
    VITE_APP_PROXY_PREFIX
  } = env;

  console.log('环境变量 env -> ', env, UNI_PLATFORM);

  return {
    envDir: './env',
    base: '',
    plugins: [
      UniPages({
        dir: 'src/pages',
        exclude: ['**/components/**/**.*'],
        dts: './src/types/uni-pages.d.ts'
      }),
      UniLayouts(),
      UniPlatform(),
      UniManifest(),
      Uni(),
      UnoCSS()
    ],
    define: {
      __VITE_APP_STORE_PREFIX__: JSON.stringify('__hospitalKiosk__'),
      __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
      __VITE_APP_PROXY__: JSON.stringify(VITE_APP_PROXY),
      __VITE_APP_BUILD_TIME__: JSON.stringify(Date.now())
    },
    css: {
      preprocessorOptions: {
        scss: {
          quietDeps: true,
          api: 'modern-compiler',
          silenceDeprecations: ['legacy-js-api', 'import']
        }
      }
    } as unknown as UserConfig['css'],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    server: {
      host: '0.0.0.0',
      hmr: true,
      port: Number.parseInt(VITE_APP_PORT, 10),
      proxy: JSON.parse(VITE_APP_PROXY)
        ? {
            [VITE_APP_PROXY_PREFIX]: {
              target: VITE_SERVER_BASEURL,
              secure: false,
              rewrite(path) {
                return path.replace(VITE_APP_PROXY_PREFIX, '');
              },
              changeOrigin: true
            }
          }
        : undefined
    },
    build: {
      // 方便非h5端调试
      sourcemap: VITE_SHOW_SOURCEMAP === 'true',
      target: 'es6',
      // 开发环境不用压缩
      minify: mode === 'development' ? false : 'terser',
      terserOptions: {
        compress: {
          drop_console: VITE_DELETE_CONSOLE === 'true',
          drop_debugger: true
        }
      }
    }
  } as UserConfig;
});
